package com.myhome.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author QYiXin
 * @Date 2021 10 22 00 02
 **/
public class ReportCsvUtils {
    public static void reportList(
            HttpServletResponse response,
            String[] header,
            String[] properties,
            String fileName,
            List<?> sourceList
    )throws Exception{
        if (header == null || properties == null || sourceList == null || header.length <= 0 || properties.length <= 0 || sourceList.size() <= 0) {
            return;
        }
        response.setContentType("application/csv");
        response.setCharacterEncoding("GBK");
        response.setHeader("Content-FileName", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8"));
        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
        csvWriter.writeHeader(header);
        for (Object o : sourceList) {
            csvWriter.write(o,properties);
        }
        csvWriter.close();
    }

    public static void reportListCsv(
            HttpServletResponse response,
            String[] header,
            String[] properties,
            String fileName,
            List<?> sourceList,
            CellProcessor[] PROCESSORS
    )throws Exception{
        if (header == null || properties == null || sourceList == null || header.length <= 0 || properties.length <= 0 || sourceList.size() <= 0) {
            return;
        }
        if (StringUtils.isBlank(fileName)) {
            fileName = "1.csv";
        }
        response.setContentType("application/csv");
        response.setCharacterEncoding("GBK");
        response.setHeader("Content-FileName", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8"));
        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
        csvWriter.writeHeader(header);
        for (Object o : sourceList) {
            csvWriter.write(o,properties,PROCESSORS);
        }
        csvWriter.close();
    }
}
